<style lang='scss'>

</style>
<template>
	<div>
        <div style="display: flex">
            <compWrapper title="账号信息" style="width: 50vw; margin-right: 10px; padding-right: 10px">
                <compFormQuery v-if=" type === 'query'" class="margin-top-15" :formdata="getBase" :value="formData"></compFormQuery>
                <compFormEdit v-else ref="formbase" :labelWidth="140" class="margin-top-15" :formdata="getBase" v-model="formData"></compFormEdit>
            </compWrapper>
            <compWrapper v-if="!isOther" title="授权服务" style="width: 50vw">
                <div v-if="type !== 'query'" style="padding: 15px 0 50px 50px;">
                    <Checkbox
                        :indeterminate="indeterminate"
                        :model-value="checkAll"
                        @click.prevent="handleCheckAll"
                        size="large"
                        style="margin-bottom: 15px">全选
                    </Checkbox>
                    <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange" size="large" style="display: flex; flex-flow:row wrap;">
                        <Checkbox v-for="item in serviceList" :key="item.value" :label="item.value" size="large" style="display: flex; align-items: center; width: 21vw; height: 40px">
                            <div style="display: flex; align-items: center; justify-content: space-between; width: 19vw">
                                <div style="flex 1; margin-right: 10px">{{item.label}}</div>
                                <Input placeholder="体积重系数" style="width: 7vw" v-model="item.volumeWeight" />
                            </div>
                        </Checkbox>
                    </CheckboxGroup>
                </div>
                <div v-else style="padding: 15px 0 50px 50px;">
                    <ul style="display: flex; flex-flow:row wrap;">
                        <li v-for="item in queryServiceList" :key="item.value" :label="item.value" size="large" style="display: flex; align-items: center; width: 21vw; height: 40px">
                            <div style="display: flex; align-items: center; justify-content: space-between; width: 19vw">
                                <div style="flex 1; margin-right: 10px">{{item.carrierServiceCode}}</div>
                                <div style="width: 7vw">{{item.volumeWeight || '--'}}</div>
                            </div>
                        </li>
                    </ul>
                </div>
            </compWrapper>
            <compWrapper v-if="isOther" title="添加服务" style="width: 50vw">
                <div v-if="type !== 'query'" style="padding: 15px 0 50px 50px;">
                    <ul>
                        <li style="margin-bottom: 20px">
                            <div style="display: flex">
                                <div style="flex: 0 0 40%">Service Code</div>
                                <div>是否需要上传面单</div>
                            </div>
                        </li>
                        <li v-for="(item,index) in otherServiceList" :key="index" style="margin-bottom: 10px">
                            <div style="display: flex; align-items: center;">
                                <div style="display: flex; align-items: center; flex: 0 0 38%">
                                    <div style="width: 100%">{{item.carrierServiceCode}}</div>
                                    <!-- <Input v-model="otherService.carrierServiceCode" style="margin-right: 10px"></Input>
                                    <Icon style="font-size: 20px; margin-right: 10px" type="md-checkmark" @click="addOtherService"/> -->
                                    <Icon style="font-size: 20px; font-weight: bolder;" type="ios-close" @click="deleteOtherService(item)"/>
                                </div>
                                <div>
                                    <RadioGroup v-model="item.isLabel" style="display: flex; padding-left: 10px">
                                        <Radio :label="1" style="flex: 0 0 59%">需上传面单</Radio>
                                        <Radio :label="0" style="flex: 1">无需上传</Radio>
                                    </RadioGroup>
                                </div>
                            </div>
                        </li>
                        <li>
                            <div style="display: flex; align-items: center;">
                                <div style="display: flex; align-items: center; flex: 0 0 38%">
                                    <Input v-model="otherService.carrierServiceCode" style="margin-right: 10px"></Input>
                                    <Icon style="font-size: 20px; margin-right: 10px; cursor: pointer;" type="md-checkmark" @click="addOtherService" />
                                    <Icon style="font-size: 20px; font-weight: bolder; cursor: pointer;" type="ios-close" @click="clearOtherService" />
                                </div>
                                <div>
                                    <RadioGroup v-model="otherService.isLabel" style="display: flex; padding-left: 10px">
                                        <Radio :label="1" style="flex: 0 0 59%">需上传面单</Radio>
                                        <Radio :label="0" style="flex: 1">无需上传</Radio>
                                    </RadioGroup>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
                <div v-else style="padding: 15px 0 50px 50px;">
                    <ul>
                        <li style="margin-bottom: 20px">
                            <div style="display: flex">
                                <div style="flex: 0 0 40%">Service Code</div>
                                <div>是否需要上传面单</div>
                            </div>
                        </li>
                        <li v-for="(item,index) in otherServiceList" :key="index" style="margin-bottom: 10px">
                            <div style="display: flex; align-items: center;">
                                <div style="display: flex; align-items: center; flex: 0 0 38%">
                                    <div style="width: 240px">{{item.carrierServiceCode}}</div>
                                </div>
                                <div style="padding-left: 15px">
                                    {{item.isLabel == 1?'需上传面单':'无需上传'}}
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </compWrapper>
        </div>
        <compWrapper title="分配管理" >
            <div v-if="type !== 'query'" style="padding: 50px 0 50px 50px;">
                    <div>
                        <RadioGroup v-model="formData.serviceType" style="display: flex; padding-left: 10px" @on-change="otherData={}">
                            <Radio :label="0" style="flex: 0 0 59%">Label</Radio>
                            <Radio :label="1" style="flex: 1">仓配</Radio>
                        </RadioGroup>
                    </div>
                    <div>
                        <Form class="clearfix padding-right-15 margin-top-5" :label-width="80"  ref='otherData' :model='otherData'>
                            <Row>
                                <Col span="6">
                                    <FormItem v-if="formData.serviceType == 0" prop='orgId' label="客户组织" >
                                        <Select v-model="otherData.orgId">
                                            <Option v-for="item in chooseOrgList" :key="item.value" :value="item.value">{{item.label}}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="6">
                                    <FormItem v-if="formData.serviceType == 0" prop='shipCode' label="Ship Code" >
                                        <Select v-model="otherData.shipCode">
                                            <Option v-for="item in shipCodeList" :key="item.value" :value="item.value">{{item.label}}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="2">
                                    <div v-show="formData.serviceType == 0" style="margin-left: 20px; padding-top: 8px">
                                        <a @click="addAddress">添加</a>
                                    </div>
                                </Col>
                                <Col span="6">
                                    <FormItem v-if="formData.serviceType == 1 || formData.serviceType == 2" prop='orgWarehouseId' label="仓库" >
                                        <Select v-model="otherData.orgWarehouseId" filterable>
                                            <Option v-for="item in getAdminTransferWarehouse" :key="item.id" :value="item.value">{{item.label}}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </div>
            </div>
            <div v-else style="padding: 50px 0 50px 0px;">
                <div>
                    <Form class="clearfix padding-right-15 margin-top-5" :label-width="80"  ref='otherData' :model='otherData'>
                        <Row>
                            <Col span="2">
                                <FormItem label="  " >
                                    <div>{{formData.serviceType == 0 ? 'Label' : '仓配'}}</div>
                                </FormItem>
                            </Col>
                            <Col v-if="formData.serviceType == 0" span="4">
                                <FormItem label="客户组织" >
                                    <!-- <div>{{chooseOrgList.find(item=>item.value == otherData.orgId).label}}</div> -->
                                    <div>{{otherData.orgCode}}</div>
                                </FormItem>
                            </Col>
                            <Col v-if="formData.serviceType == 0" span="4">
                                <FormItem prop='shipCode' label="Ship Code" >
                                    {{otherData.shipCode}}
                                </FormItem>
                            </Col>
                            <Col v-if="formData.serviceType == 1 || formData.serviceType == 2" span="4">
                                <FormItem prop='orgWarehouseId' label="仓库" >
                                    <!-- {{getAdminTransferWarehouse.find(item=> item.value == otherData.orgWarehouseId).label}} -->
                                    <div>{{otherData.orgWarehouseId}}</div>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </div>
            </div>
        </compWrapper>
        <compWrapper title="附加服务" v-if="!isOther">
            <div v-if="type !== 'query'" style="padding: 50px 0 50px 50px;">
                <CheckboxGroup v-model="formData.additionalService" style="display: flex; padding-left: 20px">
                    <Checkbox :label="'calculate'" :disabled="type == 'query'" style="flex: 0 0 33%">测算服务</Checkbox>
                    <Checkbox :label="'bill'" :disabled="type == 'query'" style="flex: 1">账单自动获取</Checkbox>
                </CheckboxGroup>
                <div>
                    <Form class="clearfix padding-right-15 margin-top-5" :label-width="80"  ref='otherData' :model='otherData'>
                        <Row>
                            <Col span="8">
                            </Col>
                            <Col span="4">
                                <FormItem v-if="formData.additionalService.indexOf('bill') >= 0" prop='billUser' label="USER ID" >
                                    <Input v-model="formData.billUser" :disabled="type == 'query'" />
                                </FormItem>
                            </Col>
                            <Col span="4">
                                <FormItem v-if="formData.additionalService.indexOf('bill') >= 0" prop='billPassword' label="PASSWORD" >
                                    <Input v-model="formData.billPassword" :disabled="type == 'query'" />
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </div>
            </div>
            <div v-else style="padding: 50px 0 50px 0px;">
                <div>
                    <Form class="clearfix padding-right-15 margin-top-5" :label-width="100"  ref='otherData' :model='otherData'>
                        <Row>
                            <Col v-if="formData.additionalService.indexOf('calculate') >= 0" span="3">
                                <FormItem label="测算服务:">
                                    <div>是</div>
                                </FormItem>
                            </Col>
                            <Col v-if="formData.additionalService.indexOf('bill') >= 0" span="3">
                                <FormItem label="账单自动获取:">
                                    <div>是</div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col v-if="formData.additionalService.indexOf('calculate') >= 0" span="3">
                            </Col>
                            <Col v-if="formData.additionalService.indexOf('bill') >= 0" span="3">
                                <FormItem label="USER ID" >
                                    <div>{{formData.billUser}}</div>
                                </FormItem>
                            </Col>
                            <Col v-if="formData.additionalService.indexOf('bill') >= 0" span="3">
                                <FormItem label="PASSWORD" >
                                    <div>{{formData.billPassword}}</div>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </div>
            </div>
        </compWrapper>
        <compWrapper title="操作历史" v-if=" type === 'query' ">
			<compLog class="margin-15" :data="opLogList" :columns="logcolumn"></compLog>
		</compWrapper>
		<div v-if="type!='query'" class="text-right margin-top-10">
			<Button type="primary" @click="submit">保存</Button>
			<Button class="margin-left-10" @click="onCancel">返回</Button>
		</div>
		<Spin v-if="loading" fix></Spin>
	</div>
</template>

<script>
import {  HttpCarrierAccountDetail, HttpCarrierAccountSave, HttpSysCarrierServiceList, HttpShipCodeList, HttpOrgList } from '@/service/api/views';
import { mapGetters } from "vuex";
import mixins from '../mixin'

export default {
	props:['querytype','activeid'],
    mixins: [ mixins ],
	data() {
		return {
            type: this.querytype || this.$route.params.type,
            id: this.activeid || this.$route.query.id,
            carrierId: this.$route.query.carrierId,
            carrierGroupId: this.$route.query.carrierGroupId,
            loading: false,
            formData: {
                type: 0,
                additionalService: [],
                serviceType: 0,
            },
            opLogList: [],
            otherData: {},
            indeterminate: false,
            checkAll: false,
            checkAllGroup: [],
            serviceList: [],
            queryServiceList: [],
            shipCodeList: [],
            otherService: {
                isLabel: 1
            },
            otherServiceList: [],
            chooseOrgList: [],
		};
	},
	async created() {
        await HttpOrgList().then(res=>{
            this.chooseOrgList = res.data.map(item=>{
                return {
                    value: item.id,
                    label: item.name,
                    attach: {
                        code: `${item.code}`
                    }}
            })
            this.getDetail();
        })
	},
    watch: {
        'otherData.orgId'(val) {
            if(val){
                this.getShipCodeList()
            }
		},
        'formData.additionalService'(val) {
            if(val.indexOf('bill') < 0){
                this.formData.billUser = ''
                this.formData.billPassword = ''
            }
        }
    },
	computed: {
         ...mapGetters('dictionary',['getSysAllList', 'getAdminTransferWarehouse','getBillcusorgList']),
        isFedEx() {
            return this.formData.carrierCode == 'FedEx';
        },
        isUPS() {
            return this.formData.carrierCode == 'UPS';
        },
        isOther() {
            return this.formData.carrierCode !== 'FedEx' && this.formData.carrierCode !== 'UPS';
        },
		getBase() {
			return [
                {
                    label: 'Carrier',
                    key: 'carrierCode',
                    query: true,
                    show: this.isFedEx || this.isUPS
                },
                {
                    label: '物流产品',
                    key: 'serviceCode',
                    query: true,
                },
                {
                    label: 'CarrierType',
                    key: 'carrierType',
                    tag: 'Select',
                    options: [
                        { label: '快递', value: 0},
                        { label: '卡车', value: 1},
                    ],
                    show: this.isOther
                },
                {
                    label: 'Carrier',
                    key: 'carrierCode',
                    show: this.isOther
                },
                {
                    label: '对接方式',
                    key: 'type',
                    tag: 'Select',
                    options: [
                        { label: '老接口', value: 0},
                        { label: '新接口', value: 1},
                    ],
                    show: this.isFedEx,
                },
                {
                    label: 'Account No',
                    key: 'accountNumber',
                    show: (this.isFedEx && this.formData.type == 0) || this.isUPS
                },
                {
                    label: 'Account Key',
                    key: 'accountKey',
                    show: (this.isFedEx && this.formData.type == 0) || this.isUPS
                },
                {
                    label: 'Password',
                    key: 'password',
                    show: (this.isFedEx && this.formData.type == 0) || this.isUPS
                },
                {
                    label: 'MeterNumber',
                    key: 'meterNumber',
                    show: this.isFedEx && this.formData.type == 0,
                },
                {
                    label: 'accessLicenseNumber',
                    key: 'accessLicenseNumber',
                    show: this.isUPS,
                },
                {
                    label: 'HubID',
                    key: 'hubId',
                    show: this.isFedEx && this.formData.type == 0,
                },
                {
                    label: 'clientSecret',
                    key: 'clientSecret',
                    show: this.isFedEx && this.formData.type == 1,
                },
                {
                    label: 'Client ID',
                    key: 'clientId',
                    show: this.isFedEx && this.formData.type == 1,
                },
                {
                    label: 'Bill Type',
                    key: 'billType',
                    tag: 'Select',
                    options: [
                        { label: 'Bill Sender', value: 0},
                        { label: '3rd Party', value: 1},
                    ],
                    show: this.isFedEx || this.isUPS
                },
                {
                    label: 'thirdPartyAccount',
                    key: 'thirdPartyAccount',
                    show: this.formData.billType == 1
                },
                {
                    label: 'billThirdPartyCountry',
                    key: 'billThirdPartyCountry',
                    show: this.formData.billType == 1 && this.isUPS
                },
                {
                    label: 'billThirdPartyPostal',
                    key: 'billThirdPartyPostal',
                    show: this.formData.billType == 1 && this.isUPS
                },
			];
		},
        logcolumn(){
            return [
                {
                    title: this.$ct('global.common.operate_time',{defaultValue:'操作时间'}),
                    key: 'updatedAt',
                },
                {
                    title: this.$ct('global.common.operator',{defaultValue:'操作人'}),
                    key: 'updatedName',
                },
                {
                    title: this.$ct('global.common.operate_type',{defaultValue:'操作类型'}),
                    render:(h,{row})=>{
                        return this.getLogActions[row.operateType] || '--';
                    }
                },
                {
                    title: "备注",
                    key: 'remark',
                },
            ]
        }
	},
	methods: {
        addAddress(){
            var url = this.$router.resolve({
                    name: 'tmsShippingAddressUpdate',
                    params: { type: 'add' },
                });
                window.open(url.href, '_blank');
        },
        handleCheckAll () {
            if (this.indeterminate) {
                this.checkAll = false;
            } else {
                this.checkAll = !this.checkAll;
            }
            this.indeterminate = false;
            if (this.checkAll) {
                this.checkAllGroup = this.serviceList.map(item=>item.value);
            } else {
                this.checkAllGroup = [];
            }
        },
        checkAllGroupChange (data) {
            if (data.length === this.serviceList.length) {
                this.indeterminate = false;
                this.checkAll = true;
            } else if (data.length > 0) {
                this.indeterminate = true;
                this.checkAll = false;
            } else {
                this.indeterminate = false;
                this.checkAll = false;
            }
            this.serviceList.map(item=>{
                if(data.indexOf(item.value) < 0){
                    item.volumeWeight = ''
                }
            })
        },
        addOtherService(){
            if(!this.otherService.carrierServiceCode){
                this.$Message.error('请填写Service Code!');
                return
            }
            this.otherServiceList.push(this.otherService);
            this.otherService={isLabel: 1};
        },
        clearOtherService(){
            this.otherService={};
        },
        deleteOtherService(obj){
            this.otherServiceList = this.otherServiceList.filter(item => item.carrierServiceCode !== obj.carrierServiceCode)
        },
		onCancel() {
			this.$router.push({
				name: "tmsLogisticsProductsList"
			});
		},
        getServiceList(){
            HttpSysCarrierServiceList({'search[EQ_carrierId]': this.carrierId, 'search[EQ_active]': 1}).then(res=>{
                this.serviceList = res.data.map(item=>{
                    return {label: item.carrierServiceCode, value: item.carrierServiceCode, attach: item}
                })
            },err => {
				this.$Message.error(err.message);
			})
        },
        getShipCodeList(){
			this.loading = true;
            HttpShipCodeList({active: 1, contextId: this.otherData.orgId}).then(res => {
				this.loading = false;
                this.shipCodeList = res.data.map(item=>{
                    return {label: item.code, value: item.code, attach: item}
                });
			}, err => {
				this.loading = false;
				this.$Message.error(err.message);
			})
        },
		getDetail() {
            // if(this.type !== 'query'){
            //     this.getServiceList();
            // }
			if (this.type === "add" ) {
                // if(!this.isOther){
                this.formData.carrierCode = this.$route.query.carrier;
                // }
                this.formData.serviceCode = this.$route.query.code;
                this.getServiceList();
                return;
            }
			this.loading = true;
			HttpCarrierAccountDetail({
				id: this.id,
			}).then(res => {
                this.formData = res.data;
                this.formData.serviceType = res.data.serviceType == 0 ? 0 :1;
                this.formData.serviceCode = res.data.carrierGroupCode;
                this.queryServiceList = res.data.sysCarrierGroupServiceEntityList.filter(item=>item.active == 1);
                this.otherServiceList = res.data.sysCarrierGroupServiceEntityList.filter(item=>item.active == 1);
                this.otherData.orgId = res.data.organizationId;
                this.otherData.shipCode = res.data.serviceRefCode;
                this.otherData.orgWarehouseId = res.data.serviceRefCode;
                this.carrierGroupId = res.data.carrierGroupId;
                this.carrierId = res.data.carrierId;
                this.formData.additionalService = [];
                if(res.data.isCalculate) this.formData.additionalService.push('calculate');
                if(res.data.isBill) this.formData.additionalService.push('bill');
                this.opLogList = res.data.orderLogsEntityList;
                this.serviceList = res.data.sysCarrierGroupServiceEntityList.map(item=>{ return {value: item.carrierServiceCode, label: item.carrierServiceCode, volumeWeight: item.volumeWeight, attach: item}});
                this.checkAllGroup = res.data.sysCarrierGroupServiceEntityList.filter(item=> item.active == 1 ).map(item=>item.carrierServiceCode);
                let chooseOrg = this.chooseOrgList.find(item=>item.value == this.otherData.orgId);
                // let chooseWarehouse = this.getAdminTransferWarehouse.find(item=> item.value == this.otherData.orgWarehouseId);
                this.otherData.orgCode = chooseOrg ? chooseOrg.label : '--' ;
                // this.otherData.warehouseCode = chooseWarehouse ? chooseWarehouse.label : '--';
                this.loading = false;
			}, err => {
				this.loading = false;
				this.$Message.error(err.message);
			});
		},
		async submit() {
			const valid = await this.$refs.formbase.validate();
			if (!valid) return;
            let isCalculate = this.formData.additionalService.indexOf('calculate') >= 0 ? 1 : 0;
            let isBill = this.formData.additionalService.indexOf('bill') >= 0 ? 1 : 0;
            let newWerviceList = [];
            if(this.checkAllGroup.length > 0){
                newWerviceList = this.checkAllGroup.map(item=>{
                    let newService = this.serviceList.filter( item1 => item1.value === item)[0];
                    return {carrierServiceCode: item, volumeWeight: newService.volumeWeight}
                })
            }
            if(this.isOther){
                this.formData.type = 1;
            }
			this.loading = true;
			HttpCarrierAccountSave({
                ...this.formData,
                hostOrgId: global.SYSID,
                organizationId: this.otherData.orgId || global.SYSID,
                carrierGroupId: this.carrierGroupId,
                carrierId: this.carrierId,
                isCalculate,
                isBill,
                sysCarrierGroupServiceEntityList: this.isOther ? this.otherServiceList : newWerviceList,
                serviceRefCode: this.otherData.shipCode || this.otherData.orgWarehouseId,
			}).then(res => {
				this.loading = false;
                this.$Message.success(res.message)
				this.onCancel();
			}, err => {
				this.loading = false;
				this.$Message.error(err.message);
			})
		},
	}
};
</script>
